import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Conversation, Message, MessageListResponse } from '@/api/message'
import { conversationAPI, messageAPI } from '@/api/message'
import { wsManager } from '@/utils/websocket'
import { ElMessage } from 'element-plus'

export const useConversationStore = defineStore('conversation', () => {
  // 状态
  const conversations = ref<Conversation[]>([])
  const activeConversationId = ref<string | null>(null)
  const messages = ref<Map<string, Message[]>>(new Map())
  const hasMore = ref<Map<string, boolean>>(new Map())
  const loading = ref(false)
  const sendingMessage = ref(false)

  // 计算属性
  const activeConversation = computed(() => {
    return conversations.value.find(c => c.id === activeConversationId.value)
  })

  const activeMessages = computed(() => {
    if (!activeConversationId.value) return []
    return messages.value.get(activeConversationId.value) || []
  })

  const totalUnreadCount = computed(() => {
    return conversations.value.reduce((sum, conv) => sum + conv.unreadCount, 0)
  })

  // 方法
  
  /**
   * 加载会话列表
   */
  const loadConversations = async () => {
    try {
      loading.value = true
      const data = await conversationAPI.getConversations()
      conversations.value = data.sort((a, b) => {
        // 先按置顶排序，再按最后消息时间排序
        const aPinned = a.participants.find(p => p.pinned) ? 1 : 0
        const bPinned = b.participants.find(p => p.pinned) ? 1 : 0
        
        if (aPinned !== bPinned) {
          return bPinned - aPinned
        }
        
        const aTime = a.lastMessage?.createdAt || a.createdAt
        const bTime = b.lastMessage?.createdAt || b.createdAt
        return new Date(bTime).getTime() - new Date(aTime).getTime()
      })
    } catch (error: any) {
      ElMessage.error(error.message || '加载会话列表失败')
    } finally {
      loading.value = false
    }
  }

  /**
   * 创建会话
   */
  const createConversation = async (type: 'DIRECT' | 'GROUP', participantIds: string[], name?: string) => {
    try {
      const conversation = await conversationAPI.createConversation({
        type,
        participantIds,
        name
      })
      
      // 添加到列表
      conversations.value.unshift(conversation)
      
      // 设置为当前会话
      setActiveConversation(conversation.id)
      
      return conversation
    } catch (error: any) {
      ElMessage.error(error.message || '创建会话失败')
      throw error
    }
  }

  /**
   * 设置当前会话
   */
  const setActiveConversation = (conversationId: string | null) => {
    activeConversationId.value = conversationId
    
    if (conversationId) {
      // 加载消息
      loadMessages(conversationId)
      
      // 订阅会话消息
      subscribeToConversation(conversationId)
    }
  }

  /**
   * 加载消息
   */
  const loadMessages = async (conversationId: string, beforeTime?: string) => {
    try {
      const response: MessageListResponse = await messageAPI.getMessages(
        conversationId,
        beforeTime
      )
      
      const existingMessages = messages.value.get(conversationId) || []
      
      if (beforeTime) {
        // 加载更多，追加到末尾
        messages.value.set(conversationId, [...existingMessages, ...response.messages])
      } else {
        // 首次加载或刷新
        messages.value.set(conversationId, response.messages)
      }
      
      hasMore.value.set(conversationId, response.hasMore)
      
      // 标记为已读
      if (response.messages.length > 0) {
        markConversationAsRead(conversationId)
      }
    } catch (error: any) {
      ElMessage.error(error.message || '加载消息失败')
    }
  }

  /**
   * 加载更多消息
   */
  const loadMoreMessages = async (conversationId: string) => {
    const existingMessages = messages.value.get(conversationId) || []
    if (existingMessages.length === 0) return
    
    const oldestMessage = existingMessages[existingMessages.length - 1]
    await loadMessages(conversationId, oldestMessage.createdAt)
  }

  /**
   * 发送消息
   */
  const sendMessage = async (
    conversationId: string,
    content: string,
    messageType: string = 'TEXT',
    replyToId?: string
  ) => {
    try {
      sendingMessage.value = true
      
      const message = await messageAPI.sendMessage({
        conversationId,
        content,
        messageType: messageType as any,
        replyToId
      })
      
      // 添加到消息列表
      addMessage(conversationId, message)
      
      // 更新会话列表中的最后消息
      updateConversationLastMessage(conversationId, message)
      
      return message
    } catch (error: any) {
      ElMessage.error(error.message || '发送消息失败')
      throw error
    } finally {
      sendingMessage.value = false
    }
  }

  /**
   * 撤回消息
   */
  const recallMessage = async (messageId: string) => {
    try {
      const message = await messageAPI.recallMessage(messageId)
      
      // 更新消息列表
      const conversationMessages = messages.value.get(message.conversationId) || []
      const index = conversationMessages.findIndex(m => m.id === messageId)
      
      if (index > -1) {
        conversationMessages[index] = message
        messages.value.set(message.conversationId, [...conversationMessages])
      }
      
      ElMessage.success('消息已撤回')
    } catch (error: any) {
      ElMessage.error(error.message || '撤回失败')
    }
  }

  /**
   * 标记会话为已读
   */
  const markConversationAsRead = async (conversationId: string) => {
    try {
      await messageAPI.markConversationAsRead(conversationId)
      
      // 更新未读数
      const conversation = conversations.value.find(c => c.id === conversationId)
      if (conversation) {
        conversation.unreadCount = 0
      }
    } catch (error) {
      console.error('标记已读失败', error)
    }
  }

  /**
   * 订阅会话消息
   */
  const subscribeToConversation = (conversationId: string) => {
    wsManager.subscribeToConversation(conversationId, (data: any) => {
      if (data.action === 'NEW_MESSAGE' && data.message) {
        handleNewMessage(data.message)
      } else if (data.action === 'MESSAGE_RECALLED' && data.message) {
        handleMessageRecalled(data.message)
      }
    })
  }

  /**
   * 处理新消息
   */
  const handleNewMessage = (message: Message) => {
    // 添加到消息列表
    addMessage(message.conversationId, message)
    
    // 更新会话列表
    updateConversationLastMessage(message.conversationId, message)
    
    // 如果不是当前会话，增加未读数
    if (message.conversationId !== activeConversationId.value) {
      const conversation = conversations.value.find(c => c.id === message.conversationId)
      if (conversation) {
        conversation.unreadCount++
      }
    } else {
      // 当前会话，自动标记已读
      markConversationAsRead(message.conversationId)
    }
    
    // 播放提示音
    if (message.conversationId !== activeConversationId.value) {
      playNotificationSound()
    }
  }

  /**
   * 处理消息撤回
   */
  const handleMessageRecalled = (message: Message) => {
    const conversationMessages = messages.value.get(message.conversationId) || []
    const index = conversationMessages.findIndex(m => m.id === message.id)
    
    if (index > -1) {
      conversationMessages[index] = message
      messages.value.set(message.conversationId, [...conversationMessages])
    }
  }

  /**
   * 添加消息到列表
   */
  const addMessage = (conversationId: string, message: Message) => {
    const conversationMessages = messages.value.get(conversationId) || []
    
    // 检查是否已存在
    const exists = conversationMessages.some(m => m.id === message.id)
    if (exists) return
    
    // 添加到开头（因为消息是倒序的）
    messages.value.set(conversationId, [message, ...conversationMessages])
  }

  /**
   * 更新会话最后消息
   */
  const updateConversationLastMessage = (conversationId: string, message: Message) => {
    const conversation = conversations.value.find(c => c.id === conversationId)
    if (!conversation) return
    
    conversation.lastMessage = {
      id: message.id,
      content: message.content,
      senderId: message.senderId,
      senderName: message.senderName,
      messageType: message.messageType,
      createdAt: message.createdAt
    }
    
    // 将会话移到列表顶部
    const index = conversations.value.findIndex(c => c.id === conversationId)
    if (index > 0) {
      const [conv] = conversations.value.splice(index, 1)
      conversations.value.unshift(conv)
    }
  }

  /**
   * 播放提示音
   */
  const playNotificationSound = () => {
    const audio = new Audio('/sounds/message.mp3')
    audio.play().catch(e => console.log('播放提示音失败', e))
  }

  /**
   * 清理
   */
  const cleanup = () => {
    conversations.value = []
    messages.value.clear()
    hasMore.value.clear()
    activeConversationId.value = null
  }

  return {
    // 状态
    conversations,
    activeConversationId,
    messages,
    loading,
    sendingMessage,
    
    // 计算属性
    activeConversation,
    activeMessages,
    totalUnreadCount,
    
    // 方法
    loadConversations,
    createConversation,
    setActiveConversation,
    loadMessages,
    loadMoreMessages,
    sendMessage,
    recallMessage,
    markConversationAsRead,
    subscribeToConversation,
    cleanup
  }
})
